/**
 * 消息列表适配器，用于将消息数据绑定到ListView的item视图
 */
package com.example.gitpart03.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.gitpart03.R;
import com.example.gitpart03.entity.Msg;

import java.util.List;

public class MsgAdapter extends ArrayAdapter<Msg> {
    private int resourceId;

    /**
     * 构造方法，初始化消息适配器
     * @param context 上下文
     * @param resource item布局资源ID
     * @param objects 消息数据列表
     */
    public MsgAdapter(@NonNull Context context, int resource, @NonNull List objects) {
        super(context, resource, objects);
        resourceId = resource;
    }

    /**
     * 获取item视图，根据消息类型显示发送或接收布局
     * @param position 列表位置
     * @param convertView 复用视图
     * @param parent 父容器
     * @return 绑定数据后的item视图
     */
    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        Msg msg =getItem(position);
        View msgView = LayoutInflater.from(getContext()).inflate(resourceId,null);
        LinearLayout sendLayout =msgView.findViewById(R.id.layout_send);
        LinearLayout recLayout =msgView.findViewById(R.id.layout_rec);

        TextView sendContent =msgView.findViewById(R.id.text_send);
        ImageView sendHead =msgView.findViewById(R.id.img_send);


        TextView recContent =msgView.findViewById(R.id.text_rec);
        ImageView recHead =msgView.findViewById(R.id.img_rec);
        if (msg.getType()==0){
            sendLayout.setVisibility(ViewGroup.VISIBLE);
            recLayout.setVisibility(ViewGroup.GONE);
            sendContent.setText(msg.getContent());
            sendHead.setImageResource(msg.getHeadImgId());
        }else {
            sendLayout.setVisibility(ViewGroup.GONE);
            recLayout.setVisibility(ViewGroup.VISIBLE);
            recContent.setText(msg.getContent());
            recHead.setImageResource(msg.getHeadImgId());
        }
        return  msgView;
    }
}
